package com.storm.lib.template;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Controller;

import com.storm.lib.base.BaseDAO;
import com.storm.lib.base.BasePo;
import com.storm.lib.util.BeanUtil;
import com.storm.lib.util.ExceptionUtil;
import com.storm.lib.util.HashMapUtil;


@Controller
public class GameDataTemplate {
	public static ConcurrentHashMap<String,ConcurrentHashMap> gameDataCache = new ConcurrentHashMap();
	public static ConcurrentHashMap<String,List> gameDataListCache = new ConcurrentHashMap();
	
	public static Class[] GAMECLASS;

	/**
	 *
	 * 方法功能:初始化赋值操作
	 * 更新时间:2010-12-28, 作者:johnny
	 */
	public void init(Class[] clazz){
		GAMECLASS=clazz;
		init();
	}
	
	
	public void init(){
		initGameLists();
	}


	/**
	 *
	 * 方法功能:重新加载游戏列表
	 * 更新时间:2011-3-29, 作者:johnny
	 */
	public void initGameLists() {
		BaseDAO baseDAO = (BaseDAO) BeanUtil.getBean("baseDAO");
		for (int i = 0; i < GAMECLASS.length; i++) {
			Class theClass = GAMECLASS[i];
			List<BasePo> itemList =baseDAO.getDBList(theClass);
			ConcurrentHashMap itemMap = HashMapUtil.getHashMapFromList(itemList);
			gameDataCache.put(theClass.getSimpleName(), itemMap);
			gameDataListCache.put(theClass.getSimpleName(), itemList);
		}
		for (int i = 0; i < GAMECLASS.length; i++) {
			Class theClass = GAMECLASS[i];
			List<BasePo> itemList = gameDataListCache.get(theClass.getSimpleName());
			if(itemList==null){
				ExceptionUtil.throwInvalidParamException();
			}
			for (int j = 0; j < itemList.size(); j++) {
				itemList.get(j).loadData(null);
			}
		}
	}
	

	/**
	 *
	 * 方法功能:返回数据
	 * 更新时间:2010-12-28, 作者:johnny
	 * @param clazz
	 * @param id
	 * @return
	 */
	public BasePo getGameData(Class clazz,int id){
		ConcurrentHashMap gameMap = gameDataCache.get(clazz.getSimpleName());
		if(gameMap==null){
			ExceptionUtil.throwInvalidParamException();
		}
		BasePo basePo = (BasePo) gameMap.get(String.valueOf(id));
		return basePo;
	}

	/**
	 *
	 * 方法功能:返回数据数组
	 * 更新时间:2010-12-28, 作者:johnny
	 * @param clazz
	 * @param id
	 * @return
	 */
	public List getDataList(Class clazz){
		List  gameList = gameDataListCache.get(clazz.getSimpleName());
		if(gameList==null){
			ExceptionUtil.throwInvalidParamException(clazz.getSimpleName());
		}
		return gameList;
	}

	/**
	 * 重新加载所有数据
	 */
	public void reloadAll(){
		clear();
		init();
	}

	private void clear(){
		gameDataCache = new ConcurrentHashMap();
		gameDataListCache = new ConcurrentHashMap();

	}

}
